<?php

class Portfolios extends CI_Model {
    const IMAGE_PATH = 'assets/images/portfolio/';

    private $_table_name = 'portofolio';
    public $idportofolio;
    public $tahun;
    public $judul;
    public $deskripsi;
    public $pekerja;
    public $gambar_utama;

    function __construct() {
        parent::__construct();
        $this->tahun = date('Y');
        $this->load->database();
    }

    function build_data() {
        return array(
            'tahun' => $this->tahun,
            'judul' => $this->judul,
            'deskripsi' => $this->deskripsi,
            'pekerja' => $this->pekerja,
            'gambar_utama' => $this->gambar_utama,
        );
    }

    function delete($id) {
        $this->db->delete($this->_table_name, array('idportofolio' => $id));
    }

    function get($year = NULL) {
        if ($year != NULL) {
            $this->db->where('tahun', $year);
        }
        return $this->db->get('portofolio')->result();
    }

    /**
     * Mengambil portofolio berdasarkan id
     * @param integer $id id portofolio
     * @return Portfolios 
     */
    function get_by_id($id) {
        $query = $this->db->get_where($this->_table_name, array('idportofolio' => $id));

        if ($query->num_rows() < 1) {
            return null;
        }

        $row = $query->row();
        $this->idportofolio = $row->idportofolio;
        $this->tahun = $row->tahun;
        $this->judul = $row->judul;
        $this->deskripsi = $row->deskripsi;
        $this->pekerja = $row->pekerja;
        $this->gambar_utama = $row->gambar_utama;

        return $this;
    }

    function get_portfolio_images() {
        $portfolio_images = new Portfolio_images;
        return $portfolio_images->get($this->idportofolio);
    }

    /**
     * @return array Mengembalikan daftar tahun portofilio
     */
    function get_years() {
        $query = $this->db
                ->select('tahun')
                ->group_by('tahun')
                ->order_by('tahun', 'DESC')
                ->get('portofolio');

        $years = array();
        foreach ($query->result() as $row) {
            $years[] = $row->tahun;
        }

        return $years;
    }

    function insert() {
        return $this->db->insert('portofolio', $this->build_data());
    }

    function update() {
        $this->db->where('idportofolio', $this->idportofolio);
        $this->db->update($this->_table_name, $this->build_data());
    }

}